#!/usr/bin/python
# coding:utf-8
__author__ = 'good'
__createday__ = '2015-01-15'

import flask
from flask.ext import themes
from golsee import golsee, mymail, db
from golsee import models
from threading import Thread
from flask.ext.mail import Message
from golsee.decorators import async


def blog_render(template, **context):
    theme = flask.session.get('theme', golsee.config['DEFAULT_THEME'])
    return themes.render_theme_template(theme, template, **context)


@async
def send_async_email(msg):
    with golsee.app_context():
        mymail.send(msg)


def send_email(subject, sender, recipients, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.html = html_body
    thr = Thread(target=send_async_email, args=[msg])
    thr.start()


def send_email_attach(subject, sender, recipients, html_body, attachments):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.html = html_body
    with golsee.open_resource(attachments) as fp:
        msg.attach(attachments, 'imgs/zip', fp.read())
    thr = Thread(target=send_async_email, args=[msg])
    thr.start()


def register_mail(user):
    MAIL_USERNAME = golsee.config['MAIL_USERNAME']
    send_email(u"恭喜! %s 成功注册我的博客。" % user.email,
               MAIL_USERNAME,
               [user.email],
               blog_render("user/register_email.html",
                           user=user))


def backup_mail(attachments, msg):
    MAIL_USERNAME = golsee.config['MAIL_USERNAME']
    ADMINS = golsee.config['ADMIN_EMAIL']
    send_email_attach(u"blog的备份",
                      MAIL_USERNAME,
                      [ADMINS],
                      msg,
                      attachments=attachments)


#: 生成随机密码
def make_random_passwd(l=golsee.config['RANDOM_PASSWORD_LENGTH']):
    import random

    basicstring = '''23456789abcdefghjkmnpqrtuvwxyzABCDEFGHJKMNPQRTUVWXYZ!@#$%^&*()_+=-[]{}/'''
    pwd = ''.join(random.sample(basicstring, l))
    return pwd



